<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd(1, '0')"
            >添加权限</el-button
          >
        </div>
        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                type="text"
                v-if="scope.row.type === 1"
                @click="hAdd(2, scope.row.id)"
                >添加</el-button
              >
              <el-button type="text" @click="hEdit(scope.row.id)"
                >编辑</el-button
              >
              <el-button type="text" @click="hDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-dialog
      :title="isEdit ? '编辑权限' : '新增权限'"
      :visible.sync="showDialog"
      @close="doClose"
    >
      <el-form
        label-width="80px"
        ref="formRef"
        :model="formData"
        :rules="formRules"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description"></el-input>
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPermissionList,
  addPermission,
  delPermission,
  getPermissionDetail,
  updatePermission,
} from "@/api/permissions";
import { arrayToTree } from "@/utils/index";
export default {
  data() {
    const validateRoleName = (rule, val, callback) => {
      console.log(this.formData.id);
      let nameList = this.simpleList
        .filter((item) => item.pid === this.formData.pid)
        .map((item) => item.name);
      if (this.isEdit) {
        nameList = this.simpleList
          .filter((item) => item.id !== this.formData.id)
          .filter((item) => item.pid === this.formData.pid)
          .map((item) => item.name);
      }
      console.log(nameList);
      if (nameList.includes(val)) {
        callback(new Error(`名字${val}已被占用`));
      } else {
        callback();
      }
    };
    const validateRoleCode = (rule, val, callback) => {
      let codeList = this.simpleList.map((item) => item.code);
      if (this.isEdit) {
        codeList = this.simpleList
          .filter((item) => item.id !== this.formData.id)
          .map((item) => item.code);
      }
      if (codeList.includes(val)) {
        callback(new Error(`编号${val}已被占用`));
      } else {
        callback();
      }
    };
    return {
      permissionList: [],
      showDialog: false,
      formData: {
        enVisible: "",
        name: "",
        code: "",
        description: "",
        type: "",
        pid: "",
      },
      isEdit: false,
      simpleList: [],
      curId: "",
      formRules: {
        name: [
          { required: true, message: "权限名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "权限名称要求1-50个字符",
            trigger: "blur",
          },
          {
            validator: validateRoleName,
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "权限编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "权限编码要求1-50个字符",
            trigger: "blur",
          },
          {
            validator: validateRoleCode,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.loadPermissions();
  },
  methods: {
    async loadPermissions() {
      const res = await getPermissionList();
      console.log(res);
      this.permissionList = [...arrayToTree(res.data, "0")];
      this.simpleList = res.data.map((item) => {
        return {
          pid: item.pid,
          id: item.id,
          name: item.name,
          code: item.code,
        };
      });
    },
    hAdd(type, pid) {
      this.isEdit = false;
      this.showDialog = true;
      this.formData.type = type;
      this.formData.pid = pid;
    },
    async hEdit(id) {
      console.log(id);
      this.isEdit = true;
      this.showDialog = true;
      const res = await getPermissionDetail(id);
      console.log(res.data);
      this.formData = { ...res.data };
      delete this.formData._id;
    },
    hSubmit() {
      this.isEdit ? this.doEdit() : this.doAdd();
    },
    async doAdd() {
      try {
        const res = await addPermission(this.formData);
        console.log(res);
        this.$message.success(res.message);
        this.showDialog = false;
        this.loadPermissions();
      } catch (err) {
        this.$message.error(err.message);
      }
    },
    async doEdit() {
      try {
        const res = await updatePermission(this.formData);
        console.log(res);
        this.$message.success(res.message);
        this.showDialog = false;
        this.loadPermissions();
      } catch (err) {
        console.log(err);
        this.$message.error(err.message);
      }
    },
    doClose() {
      // 1. 强制重置表单内容
      this.formData = {
        name: "", // 名称
        code: "", // 权限标识
        description: "", // 描述
        enVisible: "0", // 开启
        pid: "", // 添加到哪个节点下
        type: "", // 类型
      };
      // 2. 清空校验
      this.$refs.formRef.resetFields();
    },
    hDel(id) {
      this.$confirm("此操作将永久删除数据,是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除成功
          this.doDel(id);
        })
        .catch(() => {
          //取消删除
          this.$message.info("已取消删除");
        });
    },
    async doDel(id) {
      try {
        const res = await delPermission(id);
        this.$message.success(res.message);
        this.loadPermissions();
      } catch (err) {
        this.$message.error(err.message);
      }
    },
  },
};
</script>